 //总页数
var totalNum = 1;
 $(function() {
     // 关联／未关联状态码
     var pageStatus = 0;
     
     // 初始化表格
     viewTable(1);

     // 选择权限
     $('.add-modal').on('click','.premiss-checked',function(){
        $(this).toggleClass('on_check');
     })
    // 全选
    $(document).on('click', 'th .checked', function() {
        if (checkStatus == 0) {
            checkStatus = 1;
            $(this).addClass('on_check');
            $(this).parents('table').first().find('td .checked').addClass("on_check");
        } else if (checkStatus == 1) {
            checkStatus = 0;
            $(this).removeClass('on_check');
            $(this).parents('table').first().find('td .checked').removeClass("on_check");
        }
    })

    $(document).on('click', 'td .checked', function() {
        $(this).toggleClass("on_check");
        if (checkStatus == 1 && $('th .checked').hasClass('on_check')) { //如果全选
            //全选复选框取消
            $('th .checked').removeClass('on_check');
        }
    })


     // 读取角色详细信息
     $(document).on('click', '.edit-role', function() {
         var thisID = $(this).children('.role-id').val();
         $('.thisID-input').val(thisID);
         console.log($('.thisID-input').val());
         $('tr').removeClass('selected');
         $(this).parents('tr').first().addClass('selected');
         var thisName = $('.selected').children('td:eq(0)').text();
         $('.role-name').val(thisName);
         var premiss = $(this).children('.permiss-val').val();
         if (premiss != undefined) {
             premiss = premiss.substring(0, premiss.length - 1);
         } else {
             premiss = "";
         }

         var premissArr = premiss.split('-');
         // for(var i=0;i<premissArr.length;i++){
         //  premissArr[i] = parseInt(premissArr[i])
         // }
         console.log(thisName);
         loading();
         $.ajax({
             url: "/epi/admin/permission/permissions",
             type: "GET",
             dataType: 'json',
             success: function(data) {
                 console.log(JSON.stringify(data));
                 loadingHide();
                 // alert(JSON.stringify(data));
                 var myTemplate = Handlebars.compile($("#premiss-template").html());
                 $('.checkbox-div').html(myTemplate(data));
                 for (var j = 0; j < $('.premiss-checked').length; j++) {
                     for (var k = 0; k < premissArr.length; k++) {
                         if (premissArr[k] == $('.premiss-checked').eq(j).children('.check-input').data("id")) {
                             $('.premiss-checked').eq(j).addClass('on_check')
                         }
                         premissArr[k] = parseInt(premissArr[k])
                     }
                 }
                 $('.submit-add input').attr('class', 'btn btn-update-submit')
                 fadeModal('.add-modal');
             },
             error: function() {
                 setAlert('系统繁忙，请刷新重试');
             }
         });
         console.log($('.premiss-checked'));
         // console.log($('.premiss-checked').length);
         // $('.role-name').val(thisName);
     })

     // 删除角色
     $(document).on('click', '.delete-role', function() {
         loading();
         var thisID = $(this).children('.role-id').val();
         setConfirm('是否确认删除该角色', function() {
             $.ajax({
                 url: "/epi/admin/role/" + thisID,
                 type: "POST",
                 data: {
                     _method: "DELETE"
                 },
                 traditional: true,
                 dataType: 'json',
                 success: function(data) {
                     loadingHide();
                     console.log(JSON.stringify(data));
                     var status = data.status;
                     console.log(status == 200);
                     if (status == 500) {
                         setAlert('非法操作！');
                     } else if (status == 400) {
                         setAlert('删除失败！');
                     } else if (status == 200) {
                         setAlert('删除成功');
                         viewTable(1);
                     } else {
                         setAlert('系统繁忙，请刷新重试');
                     }
                 },
                 error: function() {
                     setAlert('系统繁忙，请刷新重试');
                 }
             });
         })
     })

     // 关联员工模态框
     $(document).on('click', '.link-role', function() {
         //默认显示已关联的员工
         pageStatus = 0;
         var $staffType = $('.staff-type button');
         $staffType.removeClass('active');
         $staffType.eq(0).addClass('active');

         var thisID = $(this).children('.role-id').val();
         $('.staff-type').data("role-id", thisID);
         // $('.thisID-input').val(thisID);
         viewLinkStaff(1);
         // $('.checked').eq(2).attr('class','check staff-check on_check');
         $('.staff-checked').removeClass('on_check');
         fadeModal('.link-modal');
     })


     // 切换已关联和未关联员工列表
     $('.staff-type .btn').click(function() {
         var a = $('.staff-type .btn').index(this);

         checkStatus = 0; //全选状态归0
         $('.checked').removeClass('on_check');

         if (a == 0) {
             viewLinkStaff(1);
             pageStatus = 0;
             $('.btn-link').val('取消关联');
         } else if (a == 1) {
             viewNotLinkStaff(1);
             pageStatus = 1;
             $('.btn-link').val('关联员工');
         }
         $('.linkPage-input').val(1);
         $('.staff-type .btn').removeClass('active');
         $(this).addClass('active');
     })


     //添加角色模态框
     $('.btn-add').click(function() {
         $('.role-name')[0].value = '';
         $('.premiss-checked').removeClass('on_check');
         $('.add-modal .submit-add input').attr('class', 'btn btn-add-submit')
         viewPremiss();
     })

     $('.btn-submit').click(function(){
        $('.link-modal,.mask').fadeOut();
     })
     //确认新增角色
     $(document).on('click', '.btn-add-submit', function() {
         var roleName = $('.role-name').val();
         var checked = $('.premiss-checked.on_check');
         var Permissions = [];
         if (roleName == '') {
             setAlert('请输入角色名')
         }else if(roleName == 'admin'){
            setAlert('角色名不可为admin');
         } else {
             for (var i = 0; i < checked.length; i++) {
                console.log(checked.eq(i).children('.check-input').data("id"))
                 var thisID = parseInt(checked.eq(i).children('.check-input').data("id"));
                 if(!isNaN(thisID)){
                    Permissions.push(thisID);
                 }
                 
             }
             console.log(Permissions);
             //防止测试报错
             // if (isNaN(Permissions[0])) {
             //     Permissions = [];
             //     Permissions[0] = 1;
             //     Permissions[1] = 2;
             // }
             loading();
             $.ajax({
                 url: "/epi/admin/role/",
                 traditional: true,
                 data: {
                     name: roleName,
                     permissions: Permissions
                 },
                 type: "POST",
                 dataType: 'json',
                 success: function(data) {
                     console.log(data);
                     loadingHide();
                     // console.log(JSON.stringify(data))
                     var status = data.status;
                     if (status == 500) {
                         setAlert('非法操作！');
                     } else if (status == 400) {
                         setAlert('添加失败！');
                     } else if (status == 200) {
                         setAlert('添加成功');
                         viewTable(1);
                         $('.add-modal,.mask').fadeOut();
                     } else {
                         setAlert('系统繁忙，请刷新重试');
                     }


                 },
                 error: function() {
                     setAlert('系统繁忙，请刷新重试');
                 }
             });
         }
     })

     // 确认更新角色
     $(document).on('click', '.btn-update-submit', function() {
         var roleName = $('.role-name').val();
         var checked = $('.premiss-checked.on_check');
         var Permissions = [];
         var PerName = '';
         if (roleName == '') {
             setAlert('请输入角色名')
         }else if(roleName == 'admin'){
            setAlert('角色名不可为admin');
         } else {
             console.log(checked.length);
             for (var i = 0; i < checked.length; i++) {
                 var thisID = parseInt(checked.eq(i).children('.check-input').data("id"));
                 Permissions.push(thisID);
                 PerName += checked.eq(i).next().first().text() + '  ';
             }

             //防止测试报错
             if (isNaN(Permissions[0])) {
                 Permissions = [];/*
                 Permissions[0] = 1;
                 Permissions[1] = 2;*/
             }
             loading();
             console.log(Permissions)
             $.ajax({
                 url: "/epi/admin/role/" + $('.thisID-input').val(),
                 type: "POST",
                 traditional: true,
                 data: {
                     _method: 'PUT',
                     name: roleName,
                     Permissions: Permissions
                 },
                 dataType: 'json',
                 success: function(data) {
                     console.log(JSON.stringify(data));
                     //alert(JSON.stringify(data))
                     loadingHide();
                     var status = data.status;
                     if (status == 500) {
                         setAlert('非法操作！');
                     } else if (status == 400) {
                         setAlert('更新失败！');
                     } else if (status == 200) {
                         setAlert('更新成功');
                         $('.selected td:eq(0)').html(roleName);
                         $('.selected td:eq(1)').html(PerName);
                         $('.add-modal,.mask').fadeOut();
                         viewTable(1)
                     } else {
                         setAlert('系统繁忙，请刷新重试');
                     }


                 },
                 error: function() {
                     setAlert('系统繁忙，请刷新重试');
                 }
             });
         }
     })

     // 搜索员工
     $('.search-btn').click(function() {
         if (pageStatus == 0) {
             viewLinkStaff(1)
         } else if (pageStatus == 1) {
             viewNotLinkStaff(1)
         }

     })

     // 关联／取消关联员工
     $('.btn-link').click(function() {
             var staffIdArr = [];
             var staffNameArr = [];
             var $checked = $('.staff-checked.on_check');
             for (var i = 0; i < $checked.length; i++) {
            	 staffIdArr.push($checked.eq(i).data("id"));
                 staffNameArr.push($checked.eq(i).data("name"));
             }
             var roleId = $('.staff-type').data("role-id");
             //所操作员工id数组
             console.log(staffIdArr);
             //角色ID
             console.log(roleId);
             //-----------------------------------
             if (pageStatus == 0) { //关联，取消关联
                 var options = getBASEDELETEAJAX();
                 options.url = "/epi/admin/role/" + roleId + "/staffs";
                 options.data.staffIds = staffIdArr;
                 console.log(options.data);
                 options.success = function(data) {
                     loadingHide();
                     setAlert("取消关联成功！");
                     viewLinkStaff();

                 };
                 options.error = function() {
                     setAlert('系统繁忙，请刷新重试');
                 };
                 $.ajax(options);
             } else if (pageStatus == 1) { //未关联
                var content = "";
                for(var i=0;i<staffIdArr.length;i++){
                    content +=  '<h5 class="account-title">'+staffNameArr[i]+'</h5>'+
                                '<div class="form-control">'+
                                    '<span class="input-title">账号:</span>'+
                                    '<input type="text" value="" class="m-account input-text"  data-id="'+staffIdArr[i]+'">'+
                                '</div>'
                }
                $('.accounts-outer').html(content);
                fadeModal('.account-modal')
             }
         })
         // 翻页－下一页
     $('.paging .next').click(function() {
             checkStatus = 0; //全选状态归0
             $('.checked').removeClass('on_check');
             $('.linkPage-input')[0].value++;

             console.log("当前页码：" + $('.linkPage-input')[0].value);

             if (pageStatus == 0) {
                 viewLinkStaff($('.linkPage-input').val());
             } else if (pageStatus == 1) {
                 viewNotLinkStaff($('.linkPage-input').val());
             }
         })
         // 翻页－上一页
     $('.paging .pre').click(function() {
         checkStatus = 0; //全选状态归0
         $('.checked').removeClass('on_check');
         console.log("当前页码：" + $('.linkPage-input')[0].value)
         if ($('.linkPage-input')[0].value > 1) {
             $('.linkPage-input')[0].value--;
             if (pageStatus == 0) { //已关联
                 viewLinkStaff($('.linkPage-input').val());
             } else if (pageStatus == 1) {
                 viewNotLinkStaff($('.linkPage-input').val());
             }
         } else {
             setAlert('已至第一页');
         }
     })

     // 跳转页
     $('.go-btn').click(function(){
        var pgNum = parseInt($('.goPage').val());
        if(isNaN(pgNum)){
            setAlert('请正确输入页码');
        }else if(pgNum>totalNum || pgNum<1){
            setAlert('无此页');
        }else{
            if (pageStatus == 0) { //已关联
             viewLinkStaff(pgNum);
         } else if (pageStatus == 1) {
             viewNotLinkStaff(pgNum);
         }
        }
        
     })

     //确认分配账号密码
     $('.btn-account').click(function() {
        var $account = $('.m-account');
        var staffIds = [];
        var usernames = [];
        for(var i=0;i<$account.length;i++){
            staffIds.push($account.eq(i).data("id"));
            usernames.push($account.eq(i).val());
        }
        var roleId = $('.staff-type').data("role-id");
        console.log(staffIds); //员工id数组
        console.log(usernames); //员工账号
        console.log(roleId);//角色id
        
        var options2 = getBASEPOSTAJAX();
         options2.url = "/epi/admin/role/" + roleId + "/staffs";
         options2.data.staffIds = staffIds;
         options2.data.usernames = usernames;
         console.log(options2.data);
         options2.success = function(data) {
             loadingHide();
             setAlert("关联成功！");
             $('.account-modal').fadeOut();
             viewNotLinkStaff();
         };
         options2.error = function() {
             setAlert('系统繁忙，请刷新重试');
         };
         $.ajax(options2);

         
     });

     //取消分配账号密码
     $('.account-cancel').click(function() {
         $('.account-modal').fadeOut();
     })

     //修改账号模态框
     $('.link-modal').on('click', '.edit-account', function() {
         //获取id
         var id = $(this).data("id");
         var name = $(this).data("name");
         var account = $(this).data("account");
         console.log(account);
         $('.account-title').html(name);
         $('.account-title').data("id", id);
         $('.m-account').val(account);
         $('.account-modal').fadeIn();
     })

     //重置密码
     $('.link-modal').on('click', '.edit-password', function() {
             //获取id
             var id = $(this).data("id");
             var roldId = $('.staff-type').data("role-id");
             setConfirm('是否确定重置密码', function() {
                 var options = getBASEPUTAJAX();
                 options.url = "/epi/admin/role/pwd";
                 options.data.pids = [id];
                 options.data.rids = [roldId];
                 console.log(options.data);
                 options.success = function(data) {
                     loadingHide();
                     var status = data.status;
                     console.log(status == 200);
                     if (status == 500) {
                         setAlert('非法操作！');
                     } else if (status == 400) {
                         setAlert('重置失败！');
                     } else if (status == 200) {
                         setAlert('重置密码成功');
                     } else {
                         setAlert('系统繁忙，请刷新重试');
                     }

                 };
                 options.error = function() {
                     setAlert('系统繁忙，请刷新重试');
                 };
                 $.ajax(options);
             })
         })
     

 })

 /**
  * [viewPremiss 显示权限]
  */
 function viewPremiss() {
     loading();
     $.ajax({
         url: "/epi/admin/permission/permissions",
         type: "GET",
         dataType: 'json',
         success: function(data) {
             console.log("permissions=" + data);
             loadingHide();
             var myTemplate = Handlebars.compile($("#premiss-template").html());
             $('.checkbox-div').html(myTemplate(data));
             fadeModal('.add-modal');
         },
         error: function() {
             setAlert('系统繁忙，请刷新重试');
         }
     });
 }

 /**
  * [viewTable 显示角色表格]
  * @param  {[int]} pageNum [页码]
  * @param  {[int]} records [每页记录数]
  */
 function viewTable(pageNum, records) {
     if (records == undefined) {
         records = 20;
     }
     loading();
     $.ajax({
         url: "/epi/admin/role/roles" + "/" + pageNum + "/" + records,
         type: "GET",
         dataType: 'json',
         success: function(data) {
             console.log(JSON.stringify(data));
             loadingHide();
             var myTemplate = Handlebars.compile($("#table-template").html());
             // console.log(myTemplate(data));
             $('.role-body').html(myTemplate(data));
         },
         error: function() {
             setAlert('系统繁忙，请刷新重试');
         }
     });
 }

 /**
  * [viewLinkStaff 查看角色已拥有的员工]
  * @param  {[type]} pageNum [description]
  * @param  {[type]} records [description]
  * @return {[type]}         [description]
  */
 function viewLinkStaff(pageNum, records) {
	 if(pageNum == undefined){
		 pageNum = 1;
	 }
     if (records == undefined) {
         records = 8;
     }
     loading();
     var roleId = $('.staff-type').data("role-id");
     console.log(roleId);

     $.ajax({
         url: "/epi/admin/role/" + roleId + "/" + pageNum + "/" + records,
         data: {
             key: $('.search-input').val()
         },
         type: "GET",
         dataType: 'json',
         success: function(data) {
            $('.crt-page-num').html(pageNum);
            console.log(data);
            if(data.length>0){
                totalNum = data[0].count;
            }else{
            	totalNum = 1;
            }
            $('.total-page-num').html(totalNum);
             console.log(data);
             loadingHide();
             var myTemplate = Handlebars.compile($("#link-staff-template").html());
             console.log(data);
             // console.log(myTemplate(data));
             $('.staff-all').html(myTemplate(data));
         },
         error: function() {
             setAlert('系统繁忙，请刷新重试');
         }
     });
 }



 /**
  * [viewNotLinkStaff 查询未关联角色的用户]
  * @param  {[type]} pageNum [description]
  * @param  {[type]} records [description]
  * @return {[type]}         [description]
  */
 function viewNotLinkStaff(pageNum, records) {
	 if(pageNum == undefined){
		 pageNum = 1;
	 }
     if (records == undefined) {
         records = 8;
     }
     var roleId = $('.staff-type').data("role-id");
     console.log(roleId);
     loading();
     $.ajax({
         url: "/epi/admin/role/" + roleId + "/" + pageNum + "/" + records + "/unrelated",
         type: "GET",
         data: {
             key: $('.search-input').val()
         },
         dataType: 'json',
         success: function(data) {
            $('.crt-page-num').text(pageNum);
            if(data.length>0){
                totalNum = data[0].count;
            }else{
            	totalNum = 1;
            }
            $('.total-page-num').text(totalNum); 
             console.log(JSON.stringify(data));
             loadingHide();
             var myTemplate = Handlebars.compile($("#not-link-staff-template").html());
             // console.log(myTemplate(data));
             console.log(data);
             $('.staff-all').html(myTemplate(data));
         },
         error: function() {
             setAlert('系统繁忙，请刷新重试');
         }
     });
 }

// ===============分页===================
